package fr.umlv.escapeir.gesture;

import java.awt.geom.Rectangle2D;

public class Square implements Mask {

	private static final int TOLERANCE = 30;

	@Override
	public boolean isValid(Gesture g) {

		int nbElement = g.size();

		int indexMinX = g.indexMinX();
		int indexMaxX = g.indexMaxX();
		int indexMinY = g.indexMinY();
		int indexMaxY = g.indexMaxY();

		int xMin = g.getX(indexMinX); // Minimum value of X from Gesture g (argument)
		int xMax = g.getX(indexMaxX); // Maximum value of X from Gesture g (argument)
		int yMin = g.getY(indexMinY); // Minimum value of Y from Gesture g (argument)
		int yMax = g.getY(indexMaxY); // Maximum value of Y from Gesture g (argument)

		int width = xMax - xMin; // Width of the form define by the Gesture g (argument)
		int height = yMax - yMin; // Height of the form define by the Gesture g (argument)

		if(width < TOLERANCE || height < TOLERANCE) return false;
		
		int xStart = g.getX(0);
		int yStart = g.getY(0);
		int xEnd = g.getX(nbElement - 1);
		int yEnd = g.getY(nbElement - 1);

		if(Math.abs(xStart - xEnd) < TOLERANCE && Math.abs(yStart - yEnd) < TOLERANCE) {

			Rectangle2D.Double rectMax = new Rectangle2D.Double(xMin - TOLERANCE, yMin - TOLERANCE, width + 2 * TOLERANCE, height + 2 * TOLERANCE);
			Rectangle2D.Double rectMin = new Rectangle2D.Double(xMin + TOLERANCE, yMin + TOLERANCE, width - 2 * TOLERANCE, height - 2 * TOLERANCE);

			for(int i = 0; i < g.size(); i++) {
				int x = g.getX(i);
				int y = g.getY(i);
				if(!(rectMax.contains(x, y) && !rectMin.contains(x, y))) return false;
			}
			g.setGestureValid(Masks.SQUARE, Direction.UNDEFINED);
			return true;

		}
		return false;
	}
}